package com.example.design.limit;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class PriorityLimiter<T> {

    private ExecutorService executor;

    // 限流器
    private Runnable limit;

    public PriorityLimiter(int threads, int queues, Runnable limit) {
        // TODO 此处需要考虑拒绝策略
        this.executor = new ThreadPoolExecutor(threads, threads, 0L, TimeUnit.SECONDS, new PriorityBlockingQueue<>(queues));
        this.limit = limit;
    }

    public T execute(PriorityTask<T> task) throws InterruptedException, ExecutionException {
        this.limit.run();
        Future<T> future = this.executor.submit(task);
        // TODO 此处需要考虑超时策略
        return future.get();
    }

}
